'use client'
import React, { useState, useEffect, useContext } from 'react';
import { useRouter, useParams, useSearchParams } from 'next/navigation';
import AuthContext from '../../../context/AuthContext';
import { get, post, update } from '../../../utils/axios';

export default function BlogEditor() {
  const router = useRouter();
  const params = useParams(); // 用于获取动态路由参数
  const searchParams = useSearchParams(); // 用于获取查询参数
  
  // 首先尝试从查询参数中获取postId，如果没有则尝试从动态路由参数中获取
  const postId = searchParams.get('postId') || params.id || params.postId;
  
  console.log('[BlogEditor] 当前路由参数:', params);
  console.log('[BlogEditor] 当前查询参数:', searchParams.toString());
  console.log('[BlogEditor] 获取到的postId:', postId);
  const { user, isAuthenticated, isLoading: authLoading, logout } = useContext(AuthContext);
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [isEditing, setIsEditing] = useState(false);

  // 监控认证状态变化
  useEffect(() => {
    console.log('[BlogEditor] 认证状态变化:', { user, isAuthenticated, authLoading });
  }, [user, isAuthenticated, authLoading]);

  useEffect(() => {
    // 检查认证状态是否加载完成
    if (!authLoading) {
      // 检查用户是否已认证
      if (!isAuthenticated) {
        console.log('[BlogEditor] 未认证用户，重定向到登录页');
        router.push('/auth/login');
        return;
      }

      // 用户已认证，继续处理
      console.log('[BlogEditor] 用户已认证，用户信息:', user);
      
      // 如果有postId，表示编辑模式
      if (postId) {
        console.log('[BlogEditor] 编辑模式，postId:', postId);
        setIsEditing(true);
        fetchPostData();
      } else {
        console.log('[BlogEditor] 新建模式');
      }
    } else {
      console.log('[BlogEditor] 等待认证状态加载...');
    }
  }, [user, isAuthenticated, authLoading, router, postId]);

  // 获取文章数据
  const fetchPostData = async () => {
    try {
      setLoading(true);
      const response = await get(`/api/post/${postId}`);
      if (response && response.data) {
        setTitle(response.data.title);
        setContent(response.data.content);
      }
    } catch (err) {
      console.error('获取文章数据失败:', err);
      setError('获取文章数据失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理表单提交
  const handleSubmit = async (e) => {
    console.log('[ handleSubmit ]-68', 123123)
    e.preventDefault();
    
    // 简单的表单验证
    if (!title.trim() || !content.trim()) {
      setError('标题和内容不能为空');
      return;
    }

    if (title.length < 2 || title.length > 100) {
      setError('标题长度应在2-100个字符之间');
      return;
    }

    if (content.length < 10) {
      setError('内容长度不能少于10个字符');
      return;
    }

    try {
      setLoading(true);
      setError('');
      
      if (isEditing) {
        // 编辑模式
        await update(`/api/post/${postId}`, { title, content });
      } else {
        // 新增模式
        await post('/api/post', { title, content });
      }
      
      // 操作成功后返回博客列表
      router.push('/blog');
    } catch (err) {
      console.error(isEditing ? '更新文章失败' : '创建文章失败', err);
      setError(isEditing ? '更新文章失败，请重试' : '创建文章失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理取消按钮点击
  const handleCancel = () => {
    router.push('/blog');
  };

  // 处理登出
  const handleLogout = () => {
    logout();
  };

  // 渲染加载界面
  const renderLoadingScreen = () => (
    <div className="min-h-screen bg-gray-50 flex items-center justify-center">
      <div className="text-xl text-gray-600">加载中...</div>
    </div>
  );

  // 渲染认证加载界面
  const renderAuthLoadingScreen = () => (
    <div className="min-h-screen bg-gray-50 flex items-center justify-center">
      <div className="text-xl text-gray-600">正在验证身份...</div>
    </div>
  );

  // 渲染主界面
  const renderMainScreen = () => (
    <div className="min-h-screen bg-gray-50">
      {/* 导航栏 */}
      <header className="bg-white shadow">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center">
              <a href="/" className="text-xl font-bold text-indigo-600">
                我的博客
              </a>
            </div>
            <div className="flex items-center">
              {user && (
                <div className="flex items-center space-x-4">
                  <span className="text-gray-700">欢迎, {user.name || user.email}</span>
                  <button 
                    onClick={handleLogout} 
                    className="bg-indigo-600 text-white px-4 py-2 rounded-md text-sm font-medium hover:bg-indigo-700"
                  >
                    登出
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-8">
          {isEditing ? '编辑文章' : '创建新文章'}
        </h1>

        {error && (
          <div className="mb-4 p-3 bg-red-100 text-red-700 rounded-md">
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-6">
          <div>
            <label htmlFor="title" className="block text-sm font-medium text-gray-700 mb-1">
              标题
            </label>
            <input
              type="text"
              id="title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="请输入文章标题"
              className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500"
              disabled={loading}
            />
            <p className="mt-1 text-sm text-gray-500">2-100个字符</p>
          </div>

          <div>
            <label htmlFor="content" className="block text-sm font-medium text-gray-700 mb-1">
              内容
            </label>
            <textarea
              id="content"
              value={content}
              onChange={(e) => setContent(e.target.value)}
              placeholder="请输入文章内容"
              rows={12}
              className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500"
              disabled={loading}
            />
            <p className="mt-1 text-sm text-gray-500">至少10个字符</p>
          </div>

          <div className="flex justify-end space-x-4 pt-4">
            <button
              type="button"
              onClick={handleCancel}
              className="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50"
              disabled={loading}
            >
              取消
            </button>
            <button
              type="submit"
              className="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700"
              disabled={loading}
            >
              {loading ? (
                <span className="flex items-center">
                  <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  处理中...
                </span>
              ) : (
                isEditing ? '更新文章' : '发布文章'
              )}
            </button>
          </div>
        </form>
      </main>
    </div>
  );

  // 根据不同状态渲染不同界面
  if (authLoading) {
    return renderAuthLoadingScreen();
  }
  
  if (loading) {
    return renderLoadingScreen();
  }

  return renderMainScreen();
}